package practise.trackerpoc.client;

import java.util.ArrayList;

import practise.trackerpoc.shared.MemberProp;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.TextBox;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class TrackerPOC implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final SearchServiceAsync searchSvc = GWT
			.create(SearchService.class);

	
	public void onModuleLoad() {
		
		FlowPanel main = new FlowPanel();
		
		//main.add(new HTML("<style size=\"16pt\"; color=\"brown\"> Tracker POC</style>"));
		main.add(new Label("Tracker POC"));
		
		final TextBox t = new TextBox();
		main.add(t);
				
		Button b = new Button("Search");
		
		final HTMLPanel resultPanel = new HTMLPanel("Results");
				
		b.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				String searchString = t.getText().toLowerCase();
				
				if (! t.equals("")) {
					resultPanel.clear();
					resultPanel.add(new HTML("fetching results..."));
					
					searchSvc.getMatchingMembers(searchString, 
							new AsyncCallback<ArrayList<MemberProp>>() {
								@Override
								public void onFailure(Throwable caught) {
									Window.alert("exception: - " + caught.getMessage());									
								}

								@Override
								public void onSuccess(ArrayList<MemberProp> members) {							
									resultPanel.clear();
									
									if (0 == members.size()) {
										resultPanel.add(new HTML("no matching results"));
									} else {
										for (MemberProp memberProp : members) {
											resultPanel.add(new HTML(memberProp.toString()));
										}
									}
								}
					});
				}
			}
		});
		
		main.add(b);				
		main.add(resultPanel);		
				
		RootLayoutPanel.get().add(main);				
	}
}
